import {reqGetUserCode,reqUserRegister,reqUserLogin,reqUserInfo,reqUserLogout,
        reqUserAddress,reqOrderInfo} from '@/api/'
import {setToken,getToken,tokenRemove} from '@/utile/token.js'
const state = {
    usercode:'',
    token:getToken(),
    userinfo:{},
    useraddress:[],
    orderinfo:{}
 };
const mutations = {
    GETUSERCODE(state,usercode){
        state.usercode = usercode;
    },
    USERLOGINTOKEN(state,token){
        state.token = token;
    },
    USERINFO(state,userinfo){
        state.userinfo = userinfo
    },
    CLEAN(state){
        state.usercode ='',
        state.userinfo ='',
        tokenRemove()
    },
    //处理userAddress数据
    USERADDRESS(state,useraddress){
        state.useraddress = useraddress
    },
    GETORDERINFO(state,orderinfo){
        state.orderinfo = orderinfo
    }
 };
const actions = { 
    async getUserCode({commit},phone){
       let result = await reqGetUserCode(phone)
       if(result.code == 200){
        commit('GETUSERCODE',result.data)
       }else{
        return Promise.reject(new Error('faile'))
       }
    },
    async userRegister({commit},data){
        console.log(data);
        let result =await reqUserRegister(data)
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('falie,注册失败'))
        }
    },
    //login中登录触发的action
    async userLogin({commit},data){
        let result =await reqUserLogin(data)
        console.log(result)
        if(result.code == 200){
            commit('USERLOGINTOKEN',result.data.token)
            setToken(result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('登录失败'))
        }
    },
    //提交token,获取用户信息
    async userInfo({commit}){
        let result = await reqUserInfo()
        if(result.code == 200){
            console.log(result,'token获得数据')
            commit('USERINFO',result.data)
        }
    },
    //退出登录操作
    async userLogout({commit}){
        let result = await reqUserLogout()
        if(result.code == 200){
            commit('CLEAN')
            return 'ok'
        }else{
            return Promise.reject(new Error('fail,退出失败'))
        }
    },
    //获取用户地址信息
    async userAddress({commit}){
        let result = await reqUserAddress()
        if(result.code == 200){
            console.log(result)
            commit('USERADDRESS',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('fail,退出失败'))
        }
    },
    //获取用户交易界面信息
    async userOrderInfo({commit}){
        let result = await reqOrderInfo()
        if(result.code == 200){
            console.log(result)
            commit('GETORDERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('fail,退出失败'))
        }
    }
};
const getters = { };
export default{
state,
mutations,
actions,
getters
}